import axios from 'axios'
import { minify } from 'html-minifier'

import { checkDir, writer } from '../utils/io'
import { info } from '../utils/output'
import { staticPath, getStaticPagePath } from '../utils/path'
import pageProcessor from '../utils/page'
import HeaderModel from '../model/header.model'
import CampusInfo from '../model/campusInfo.model'

// 文件的压缩选项
const minifyOptions = {
  minifyJS: true,
  minifyCSS: true,
  removeComments: true,
  collapseWhitespace: true,
  removeScriptTypeAttributes: true
}

const getPageResult = async (pageUrl: string, id: string, headers: HeaderModel, campusInfo: CampusInfo): Promise<void> => {
  const { name, gradeClass, username } = campusInfo
  // 解析打卡的结果页面，加工和压缩后写入文件
  info(`获取 ${username} 的打卡结果...`)
  const params = { id }
  const { data } = await axios.get(pageUrl, { params, headers: { ...headers } })
  // 写入前检查文件夹
  await checkDir(staticPath)
  await writer(getStaticPagePath(`${username}-${gradeClass}-${name}`), minify(pageProcessor(data, username), minifyOptions))
}

export default getPageResult
